"""
HTTP客户端管理模块
提供统一的HTTP连接池管理，提高并发性能
减少连接创建开销，支持连接复用
"""

import httpx
import logging
from typing import Optional
from .config import settings

logger = logging.getLogger(__name__)

# 全局HTTP客户端实例
_global_client: Optional[httpx.AsyncClient] = None


def get_http_client() -> httpx.AsyncClient:
    """
    获取全局HTTP客户端实例
    使用连接池提高并发性能，支持连接复用
    
    Returns:
        httpx.AsyncClient: 异步HTTP客户端实例
    """
    global _global_client
    if _global_client is None:
        # 创建带有连接池配置的HTTP客户端
        _global_client = httpx.AsyncClient(
            timeout=settings.request_timeout,  # 请求超时时间
            limits=httpx.Limits(
                max_keepalive_connections=20,  # 保持连接数
                max_connections=settings.max_connections,  # 最大连接数
                keepalive_expiry=30.0  # 连接保持时间（秒）
            ),
            # 启用HTTP/2支持（如果服务器支持）
            http2=True,
            # 自动重试配置
            transport=httpx.AsyncHTTPTransport(retries=2)
        )
        logger.info(f"HTTP客户端已初始化，最大连接数: {settings.max_connections}")
    return _global_client


async def close_http_client():
    """
    关闭全局HTTP客户端
    释放所有连接资源，通常在应用关闭时调用
    """
    global _global_client
    if _global_client:
        await _global_client.aclose()
        _global_client = None
        logger.info("HTTP客户端已关闭")


async def get_client_with_auth(api_key: str, auth_type: str = "Bearer") -> httpx.AsyncClient:
    """
    获取带认证头的HTTP客户端
    
    Args:
        api_key: API密钥
        auth_type: 认证类型，默认为Bearer
        
    Returns:
        httpx.AsyncClient: 配置了认证头的HTTP客户端
    """
    client = get_http_client()
    # 更新默认请求头
    client.headers.update({
        "Authorization": f"{auth_type} {api_key}",
        "Content-Type": "application/json"
    })
    return client


def reset_client_headers():
    """
    重置客户端请求头
    清除之前设置的认证信息
    """
    global _global_client
    if _global_client:
        # 重置为基本请求头
        _global_client.headers = httpx.Headers({
            "User-Agent": f"KnowYou-AI-Backend/{httpx.__version__}"
        }) 